package fun.tan90.device.sink.td.plugin.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.row.Db;
import fun.tan90.device.sink.core.SinkHandler;
import fun.tan90.device.sink.core.SinkRule;
import fun.tan90.device.sink.td.plugin.model.SinkTdRule;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SinkTdHandler extends SinkHandler {

    @Override
    public void init(List<ONode> onodeList) {
        for (ONode node : onodeList) {
            String deviceType = node.get("deviceType").getString();
            String dataSource = node.get("dataSource").getString();
            ONode sinkContext = ONode.loadStr(node.get("sinkContext").getString());
            List<SinkTdRule> sinkRules = sinkContext.ary().stream().map(n -> JSONUtil.toBean(n.toJson(), SinkTdRule.class)).collect(Collectors.toList());
            SINK_RULES.put(sinkRuleKey(deviceType, dataSource), sinkRules);
        }
    }

    @Override
    public void handle(Map<String, Object> data, Map<String, String> meta, List<? extends SinkRule> sinkRules) {
        for (SinkRule sinkRule : sinkRules) {
            SinkTdRule sinkTdRule = (SinkTdRule) sinkRule;
            String name = sinkTdRule.getName();
            String sql = StrUtil.format(sinkTdRule.getSqlTemplate(), data);
            Integer use = DataSourceKey.use(name, () -> Db.insertBySql(sql));
            log.info("[TD] row: {}", use);
        }
    }
}
